Skip to content

GROOVY-12829: a closure passes a method of Object on for a closure nested in it - #3354

Open
paulk-asert wants to merge 1 commit into
apache:masterfrom
paulk-asert:nested-closure-object-methods
Open

paulk-asert wants to merge 1 commit into
apache:masterfrom
paulk-asert:nested-closure-object-methods

Conversation

@paulk-asert

Copy link
Copy Markdown
Contributor

An implicit call of toString(), hashCode(), equals, getClass() or an
extension method of Object in a closure is first tried on the closure's
owner and delegate (GROOVY-11858, GROOVY-12576). When the owner is itself a
closure, that closure answered the call as an ordinary object, so wrapping a
call in another closure changed which object answered. An enclosing closure
now applies its own resolution rules to such a call, as it does for any other
name.

class C {
    String toString() { 'C' }
    def m() {
        def outer = { ->
            def inner = { -> toString() }
            [toString(), inner()]
        }
        outer()
    }
}
assert new C().m() == ['C', 'C']    // was ['C', 'C$_m_closure1@...']

Behaviour

toString() in a nested closure, by version (dynamic; C is the enclosing
instance, D a delegate):

Case up to 5.1.3 6.0.0 this PR
closure in a method closure C C
nested closure, or each/collect in a closure inner closure outer closure C
closure nested in new D().with { ... } inner closure outer closure D
nested in a DELEGATE_FIRST/DELEGATE_ONLY closure inner closure outer closure D
nested in a TO_SELF or dehydrated closure inner closure outer closure outer closure
  • Dynamic, @TypeChecked and @CompileStatic code now agree on every row.
    Under static compilation only toString(), hashCode(), equals and
    getClass() change; the GDK methods already reached the enclosing instance.
  • A lambda in a closure, which is a closure in dynamic code, now gives the
    same result as a statically compiled lambda there.
  • This matches a Java lambda, where a name means what it would in the
    enclosing code. Up to 5.1.3 Groovy matched a Java anonymous class instead;
    6.0.0 matched neither.

Unchanged: a closure that is not nested, any other method or property name,
the methods Closure declares, this.toString(), owner.toString(), and
toString() called on a closure from outside it.

Changes

  • ClosureMetaClass.invokeMethod: an owner or delegate that is a generated
    closure is handed the call as for one made in its own body.
  • StaticTypeCheckingVisitor: the branch that selected the owner closure's
    own method is removed, and an enclosing TO_SELF closure is added as a
    receiver for a closure nested in it.
  • @PackedClosures: a statically compiled closure making such a call in a
    nested closure now packs. The dynamic decline (GROOVY-12663) is kept, with
    its comment and message corrected.
  • Closure guide: rule 3 of "Resolution rules" says the rule holds for methods
    every object has, with a new example. The closing note states that
    statically compiled code sends a name resolved to the enclosing class to
    the this object, where dynamic code asks the owner; the two differ only
    after rehydrate.
  • COMPATIBILITY.md: an entry under Groovy 7.

Points for review

  • A delegate that is a generated closure passes the call on too, not only
    an owner.
  • Whether the dynamic GROOVY-12663 packing decline can now be removed.
  • The rehydrate sentence in the guide's note describes existing behaviour
    that is worth agreeing on.

Compatibility

Code that relies on a bare toString(), getClass(), with and the like in
a nested closure reaching the enclosing closure now reaches the enclosing
instance or delegate. owner. keeps the old result. No public API changes.

Tests

ClosuresSTCTest.testClosureObjectMethodResolveStrategy and two
PackedClosuresTransformTest cases pinned the old behaviour and are updated;
ClosuresSpecTest.testObjectMethodsInNestedClosures is new.

…sted in it

An implicit call of toString(), hashCode(), equals(), getClass() or an
extension method of Object is first tried on a closure's owner and
delegate. An owner or delegate that is itself a closure answered the
call as an ordinary object. It now applies its own resolution rules, as
for a call made in its own body, so the call reaches the enclosing
instance or a delegate however deeply the closure is nested. Static
compilation resolves such a call the same way, and an enclosing closure
with TO_SELF still answers it.
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 40.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.9564%. Comparing base (09e84fa) to head (4ff15ab).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
...aus/groovy/runtime/metaclass/ClosureMetaClass.java 33.3333% 0 Missing and 2 partials ⚠️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 50.0000% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3354        +/-   ##
==================================================
+ Coverage     74.9518%   74.9564%   +0.0047%     
- Complexity      48908      48929        +21     
==================================================
  Files            1768       1768                
  Lines          161213     161251        +38     
  Branches        31728      31742        +14     
==================================================
+ Hits           120832     120868        +36     
+ Misses          28968      28966         -2     
- Partials        11413      11417         +4     
Files with missing lines Coverage Δ
...rg/codehaus/groovy/classgen/asm/ClosureWriter.java 89.3194% <ø> (ø)
...oovy/classgen/asm/sc/StaticTypesClosureWriter.java 69.4118% <ø> (-1.1765%) ⬇️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 87.9560% <50.0000%> (+0.0389%) ⬆️
...aus/groovy/runtime/metaclass/ClosureMetaClass.java 75.8427% <33.3333%> (-0.3613%) ⬇️

... and 11 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@testlens-app

testlens-app Bot commented Nov 24, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 4ff15ab
▶️ Tests: 145274 executed
⚪️ Checks: 27/27 completed


Learn more about TestLens at testlens.app/docs.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants